Array: List of data elements
// Declare reference to an array to hold ints
int[] numbers;// Create new array to hold 6 ints
numbers = new int[6];In one step (declaring reference and creating array object in one statement):
float[] temperatures = new float[100];Array Size:
Array is accessed by:
numbers)3)// Array elements can be treated like any other variable
numbers[0] = 20;It’s very easy to by off-by-one when accessing arrays and get ArrayIndexOutOfBoundsException runtime error.
We can use an initialization list if only a few items need to be initialized, like so:
// Using an initialization list
int[] days = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
// Using a bunch of statements
days[0] = 31;
days[1] = 28;
days[2] = 31;
days[3] = 30;
days[4] = 31;
days[5] = 30;All the following is valid:
int[] numbers;
int numbers[];
int[] numbers, codes, scores;
int numbers[], codes[], scores[];Arrays are objects that have a public constant field named length that can be accessed like so:
int l = temperatures.length;Note: For other objects,
lengthis usually a method, such asString’slength()method.
for Loopfor (datatype elementVariable : array)
statement;--, +=2, etc.)elementVariable every iteration.Example:
int[] numbers = {3, 6, 9};
// Enhanced (read-only)
for (int x : numbers) {
System.out.println(x);
}
// Traditional (read/write)
for (int i = 0; i < numbers.length; i++)
{
System.out.println(numbers[i]);
}How NOT to copy an array (copying by reference):
int[] x = { 1, 2, 3 };
int[] y = x;How to copy an array (copying by value):
int[] x = { 1, 2, 3 };
int[] y = new int[x.length];
for (int i = 0; i < x.length; i++)
y[i] = x[i];Like any other object reference variable, they are passed by reference
== will only check whether two references point to the same array object.
One way to hold an unknown amount of data is to just make one big array and keep track of the end of the data with a counter variable.
A method can return a reference to an array.
Arrays aren’t limited to primitive data, they can also hold objects.
E.g.,
Rectangle[] x = new Rectangle[7];
for (int i = 0; i < x.length; i++)
x[i] = new Rectangle();String ArraysE.g.,
String[] names = { "Plutonia", "Doom2", "MyHouse" }Remember!: An array’s
lengthis a field. AString’slength()is a method.
Two-Dimensional Array: An array of arrays.
Example:
int[][] x = new int[3][4];x[2][1] = 95;ArrayList ClassUnlike an array, an ArrayList object automatically expands and shrinks when items are added and removed.
Imported with:
import java.util.ArrayList;Created with:
ArrayList<String> nameList = new ArrayList<String>();
// Alternative: Declare with different capacity than 10
ArrayList<String> nameList = new ArrayList<String>(100);<String>s tell ArrayList to store only String datatypes.Common methods:
.add().size().get().toString().remove().set()